from odoo import http, _
from odoo.http import request
import json


# from ..logs.logger_log import setup_logger
# logger = setup_logger()

class InterfaceExtensionAPI(http.Controller):

    # 单个
    @http.route("/api/product_details", auth='public', type='http', methods=['GET'], csrf=False)
    def get_default_code(self, **kwargs):
        idx = kwargs.get('id')
        name = kwargs.get('name')
        serial_number = kwargs.get('serial_number')
        if not name and not idx and not serial_number:
            return http.Response(json.dumps({'code': 400, 'message': '请求参数错误', 'data': {}}))
        domain = []
        if idx:
            domain.extend([('id', '=', idx)])
        if name:
            domain.extend([('name', 'ilike', name)])
        if serial_number:
            domain.extend([('serial_number', '=', serial_number)])
        # 查询产品模板
        product_obj = request.env['product.template'].sudo().search(domain, limit=1)
        if not product_obj:
            return http.Response(json.dumps({'code': 400, 'message': '暂无数据', 'data': {}}))
        # 客户商品编码
        customer_item_code_list = []
        for customer in product_obj.customer_item_code_ids.sudo():
            if customer_item_code_list:  # 目前只需要一个
                continue
            customer_item_code_list.append({
                'id': customer.id,
                'name': customer.customer_id.name,
                'customer_code': customer.customer_id.code,
                'code': customer.code,
                'customer_item_desc': customer.customer_item_desc,
                'version': customer.version,
                'recent_price': customer.recent_price,
            })
        # 生产参数
        param_line_list = self._get_attribute_dict(product_obj.param_line_ids.sudo())
        # 生产规格
        spec_line_list = self._get_attribute_dict(product_obj.spec_line_ids.sudo())
        # 采购参数
        pur_param_line_list = self._get_attribute_dict(product_obj.pur_param_line_ids.sudo())
        # 产品单位
        uom_value_list = []
        for uom in product_obj.uom_value_ids.sudo():
            uom_value_list.append({
                'id': uom.id,
                'uom_id': uom.uom_id.name,
                'uom_value': uom.uom_value,
            })
        data = self.get_product_details(product_obj)
        data.update({
            'customer_item_code_ids': customer_item_code_list,  # 客户商品代码
            'uom_value_list': uom_value_list,  # 产品单位
            'param_line_list': param_line_list,  # 生产参数
            'spec_line_ids': spec_line_list,  # 生产规格
            'pur_param_line_ids': pur_param_line_list,  # 采购参数
        })
        return http.Response(json.dumps({'code': 200, 'message': '', 'data': data}))

    @classmethod
    def get_product_details(cls, product_obj):
        # 客户信息
        crm_dict = {}
        if product_obj.crm_id:
            crm = product_obj.crm_id
            crm_dict = {
                'id': crm.id,
                'name': crm.name,
                'code': crm.partner_id.code,
                'phone': crm.phone,
                'layer': crm.layer,
                'unit_size_width': crm.unit_size_width,
                'panel_size_width': crm.panel_size_width,
                'board_thk': crm.board_thk,
                'unit_size_long': crm.unit_size_long,
                'panel_size_long': crm.panel_size_long,
                'surface_finish': crm.surface_finish,
                'pcs_in_panel': crm.pcs_in_panel,
                'board_material': crm.board_material,
                'internal_copper_thk': crm.internal_copper_thk,
                'external_copper_thk': crm.external_copper_thk,
                'utilization_rate': crm.utilization_rate,
            }
        data = {
            'id': product_obj.id,
            'product_name': product_obj.name,
            'jmi_author': product_obj.jmi_author,
            'default_code': product_obj.default_code,
            'serial_number': product_obj.serial_number,
            'version': product_obj.versions,
            'create_name': product_obj.create_uid.name,
            'final_change_name': product_obj.write_uid.name,
            'create_time': product_obj.create_date.isoformat() or None,
            'update_time': product_obj.write_date.isoformat() or None,
            'crm': crm_dict,
        }
        return data

    @classmethod
    def _get_attribute_dict(cls, params_objs):
        params_list = []
        for params in params_objs:
            params_list.append({
                'id': params.id,
                'attribute_id': params.attribute_id.name,
                'thai_name': params.thai_name,
                'eng_name': params.eng_name,
                'value_id': params.value_id.name,
                'z_thai_name': params.z_thai_name,
                'z_eng_name': params.z_eng_name,
            })
        return params_list

    # 多个
    @http.route("/api/commodity_information", auth='user', type='http', methods=['GET'], csrf=True)
    def get_default_info(self, **kwargs):
        default_code = kwargs.get('default_code')
        if not default_code:
            return http.Response(json.dumps({'code': 400, 'message': '编码参数必传', 'data': []}))
        c = request.env['product.category'].sudo().search([('code', '=', 'OPFP')])
        c |= c.child_id
        category_ids = [request.env.ref('sb_sale.semi_product_type').id,
                        request.env.ref('sb_sale.finished_product_type').id]
        category_ids.extend(c.ids)
        # 查询与 default_code 相关的产品
        product_template_list = request.env['product.template'].search([
            ('categ_id', 'in', category_ids),
            '|', '|', ('default_code', 'ilike', default_code),
            ("product_variant_ids.default_code", "ilike", default_code),
            ('name', 'ilike', default_code)
        ])

        if not product_template_list:
            return http.Response(json.dumps({'code': 400, 'message': f'查询不到产品信息: {default_code}', 'data': []}))
        # 准备返回的数据
        results = []  # 定义一个列表来存储所有产品模板的信息
        for product_template in product_template_list:
            # if not product_template.crm_id:  # 未配置客户信息
            #     continue
            customer_item_code_ids = []
            # crm_id = product_template.crm_id
            # if crm_id:
            #     customer = product_template.customer_item_code_ids.filtered(
            #         lambda x: x.customer_id.id == crm_id.partner_id.id)
            for customer in product_template.customer_item_code_ids:
                if customer_item_code_ids:  # 目前只需要一个
                    continue
                customer_item_code_ids = [{
                    'id': customer.id,
                    'name': customer.customer_id.name,
                    'customer_code': customer.customer_id.code,
                    'code': customer.code,
                    'customer_item_desc': customer.customer_item_desc,
                    'version': customer.version,
                    'recent_price': customer.recent_price,
                }]
            data = self.get_product_details(product_template)

            data.update({
                'create_name': product_template.create_uid.name,
                'final_change_name': product_template.write_uid.name,
                'create_time': product_template.create_date.isoformat(),
                'update_time': product_template.write_date.isoformat(),
                'uom_value_list': [{
                    'id': uom.id,
                    'uom_id': uom.uom_id.name,
                    'uom_value': uom.uom_value,
                } for uom in product_template.uom_value_ids],  # 产品单位
                'param_line_list': self._get_attribute_dict(product_template.param_line_ids),  # 生产参数
                'spec_line_ids': self._get_attribute_dict(product_template.spec_line_ids),  # 生产规格
                'pur_param_line_ids': self._get_attribute_dict(product_template.pur_param_line_ids),  # 采购参数
                'customer_item_code_ids': customer_item_code_ids
            })
            results.append(data)  # 将每个产品模板的信息添加到结果列表中

        return http.Response(json.dumps(results), content_type='application/json')  # 返回所有产品模板的信息

    @http.route("/api/material/grade", auth='user', type='json', methods=['POST', 'OPTIONS'], csrf=False)
    def get_material_grade(self, **kwargs):
        """
        产品升级, 接口弃用
        """
        # api_records = {
        #     'api_params': kwargs,
        #     'api_user_id': False,
        #     'api_route': '/api/material/grade',
        #     'state': 'success',
        #     'result_json': False
        # }
        # request.env['api.records'].sudo().create(api_records)
        # product_code = kwargs.get('code')
        # name_zh = kwargs.get('name_zh')
        # name_en = kwargs.get('name_en')
        # new_code = kwargs.get('new_code')
        # version = kwargs.get('version')
        # product = request.env['product.template'].sudo().search([('default_code', '=', product_code)], limit=1)
        # if not product:
        #     return {'code': 400, 'message': _('The product code does not exist')}
        # new_product = product.copy()
        # dtl = {
        #     'default_code': new_code,
        #     'name': name_zh,
        #     'description_eng': name_en,
        #     'versions': version,
        # }
        # customer_item_code_ids = product.customer_item_code_ids
        # if customer_item_code_ids:
        #     item = customer_item_code_ids[0]
        #     # 新建客户编码
        #     code = request.env['customer.item.code'].sudo().create({
        #         'code': item.code,
        #         'product_id': new_product.id,
        #         'customer_id': item.customer_id.id,
        #         'customer_item_desc': item.customer_item_desc,
        #         'version': version,
        #         'recent_price': item.recent_price,
        #     })
        #     dtl.update({
        #         'customer_item_code_ids': [(6, 0, code.ids)]
        #     })
        # item_code_ids = []
        # for item in product.customer_item_code_ids:
        #     code = request.env['customer.item.code'].sudo().create({
        #         'code': item.code,
        #         'product_id': new_product.id,
        #         'customer_id': item.customer_id.id,
        #         'customer_item_desc': item.customer_item_desc,
        #         'version': version,
        #         'recent_price': item.recent_price,
        #     })
        #     item_code_ids.append(code.id)
        # dtl.update({
        #     'customer_item_code_ids': [(6, 0, item_code_ids)]
        # })
        # new_product.write(dtl)
        # data = {
        #     'id': new_product.id,
        #     'code': new_product.default_code,
        #     'name': new_product.name,
        #     'version': new_product.versions,
        # }
        return {'code': 200, 'message': 'success', 'result': {}}
